package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.mvp.contract.PropertyFeeContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.ProperFeeEvent;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.FeeOverdueViewAdapter;
import com.dindang.propertyfee.mvp.ui.adapter.custom.OverdueViewAdapter;
import com.dindang.propertyfee.mvp.ui.widget.manager.FullyGridLayoutManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@FragmentScope
public class PropertyFeePresenter extends BasePresenter<PropertyFeeContract.Model, PropertyFeeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private boolean isFirst = true;
    private List<PropertyCharge.Recent> mRecentList = new ArrayList<>();
    private List<PropertyCharge.Overdue> mOverdueList = new ArrayList<>();
    private OverdueViewAdapter mOverdueViewAdapter;
    private FeeOverdueViewAdapter mFeeOverdueViewAdapter;
    private ProperFeeEvent properFeeEvent = new ProperFeeEvent();

    @Inject
    public PropertyFeePresenter(PropertyFeeContract.Model model, PropertyFeeContract.View rootView) {
        super(model, rootView);
    }

    public void setData(Object data) {
        switch (data.toString()) {
            case "init":
                if(isFirst){
                    getDate();
                    isFirst = false;
                }
                break;
            case "refresh":
                break;
        }
    }

    public void init() {
        EventBus.getDefault().register(this);
        initView();
        initListener();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void MaintainDetailsRefresh(ProperFeeEvent taskEvent){
        getDate();
    }

    private void initView() {
        mRootView.getRvExpire().setNestedScrollingEnabled(false);
        mRootView.getRvExpire().setFocusable(false);
        mRootView.getListview().setNestedScrollingEnabled(false);
        mRootView.getListview().setFocusable(false);

        FullyGridLayoutManager manager = new FullyGridLayoutManager(mRootView.getRvExpire().getContext(), 2, GridLayoutManager.VERTICAL, false);
        mRootView.getRvExpire().setLayoutManager(manager);
        mOverdueViewAdapter = new OverdueViewAdapter(mRecentList, new OverdueViewAdapter.OnClickListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.Recent recent = mRecentList.get(position);
                ARouter.getInstance().build("/propertyfee/activity/FeeList2Activity").withString(AppConst.DUE_TO, recent.name).navigation();
            }
        });
        mRootView.getRvExpire().setAdapter(mOverdueViewAdapter);

        mFeeOverdueViewAdapter = new FeeOverdueViewAdapter(mOverdueList,
        new FeeOverdueViewAdapter.OnFeeOverdueListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.Overdue overdue = mOverdueList.get(position);
                ARouter.getInstance().build("/propertyfee/activity/ReceivableDetailActivity")
                        .withString(AppConst.ID, overdue.c_nodedate_id)
                        .withString(AppConst.RECEIVABLEDETAIL_ADDRESS, overdue.bName + "/" + overdue.addr)
                        .withString(AppConst.RECEIVABLEDETAIL_NAME_TEL, overdue.custName + "/" + overdue.c_telphone)
                        .navigation();
            }
        });
        mRootView.getListview().setAdapter(mFeeOverdueViewAdapter);
    }

    private void initListener() {
        mRootView.getViewSearch().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/propertyfee/activity/OwnerSearchActivity").navigation();
            }
        });

        mRootView.getTvMore().setOnClickListener(v ->
                ARouter.getInstance().build("/propertyfee/activity/FeeList2Activity").withString(AppConst.DUE_TO, "已逾期").navigation());
    }

    private void initData() {
    }

    /**
     * 模拟数据请求
     */
    private void getDate(){
        queryRecentCount();
        queryOverdue();
    }

    private void queryRecentCount(){
        PropertyCharge.RecentCountParam param= new PropertyCharge.RecentCountParam();
        param.corpId = BaseAppConst.accountInfo.getCorpId();
        param.page =0;
        param.rows = 10;
        mModel.queryRecentCount(new PropertyCharge.RecentCountParam())
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<PropertyCharge.RecentCount>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<PropertyCharge.RecentCount> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }
                mRecentList.clear();
                response.getData().today.setName("今日到期");
                mRecentList.add(response.getData().today);
                response.getData().tomorrow.setName("明日到期");
                mRecentList.add(response.getData().tomorrow);
                response.getData().sevenDay.setName("7日到期");
                mRecentList.add(response.getData().sevenDay);
                response.getData().thirtyDay.setName("30日到期");
                mRecentList.add(response.getData().thirtyDay);

                StringBuffer overdueStringBuffer = new StringBuffer();
                overdueStringBuffer.append(ArmsUtils.getString(mApplication, R.string.propertyfee_home_late));
                overdueStringBuffer.append(" (");
                overdueStringBuffer.append(mOverdueList.size());
                overdueStringBuffer.append("户)");
                mRootView.getTvLateHome().setText(overdueStringBuffer);

                mOverdueViewAdapter.notifyDataSetChanged();
            }
        });
    }

    private void queryOverdue(){
        PropertyCharge.OverdueParam param = new PropertyCharge.OverdueParam("100000000000",BaseAppConst.accountInfo.getCorpId());
        mModel.queryOverdue(param)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.Overdue>>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<List<PropertyCharge.Overdue>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }

                mOverdueList.addAll(response.getData());
                mFeeOverdueViewAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mRecentList = null;
        this.mOverdueList = null;
        this.mOverdueViewAdapter = null;
        this.mFeeOverdueViewAdapter = null;
    }

}
